import request from '@/base/request'
import { ElMessage } from 'element-plus'
import {ref,nextTick} from 'vue'
import Class from '@/types/class'
import Message from '@/types/message'
import { v4 as uuidv4 } from 'uuid';
export default function(){


    interface AllClass extends Class{
        joined:boolean
    }

    const status=ref<string>("与服务器连接中")
    const classSearch=ref<String>("")
    const classInfo=ref<Array<Class>>([])
    const chooseClass=ref<Class>()
    const messageList=ref<Array<Message>>([])
    const input=ref("")
    const loginUserId = localStorage.getItem("loginUserId");
    const scrollRef=ref(null)
    const allClassList=ref<Array<AllClass>>([])
    const getMessageParm=ref({
        classId:null,
        userId:null,
    })

    const allClassSearch=ref("")
    async function getUserClass(userId) {
        const response=(await request.get(`/user/class/getUserClass?userId=${userId}&input=${classSearch.value}`)).data
        if(response.code===200){
            if(userId==null)allClassList.value=response.data
            else classInfo.value=response.data
        }else{
            ElMessage.error(`获取用户班级失败，请尝试`)
        }
    }

    async function sendMessage(userName,avatar) {
        input.value=input.value.slice(0,input.value.length-1);  
        if(input.value===null || input.value===undefined || input.value.length===0){
            ElMessage({
                message:`不能为空`,
                grouping:true,
                type:'error'
            })
            input.value=""
            return
        }
        
        
        const messageParm={
            message:input.value,
            classId:chooseClass.value.id,
            avatar:avatar,
            userId:loginUserId,
            userName:userName,
            createTime:new Date()
        }
        input.value=""
        const response=(await request.post("/user/message/sendMessage",messageParm)).data
        if(response.code===200){


        }else{
            ElMessage.error(`发送失败,${response.msg}`)
        }
    }

    async function getMessage() {
        getMessageParm.value.classId=chooseClass.value.id
        const response=(await request.post("/user/message/getMessage",getMessageParm.value)).data
        if(response.code===200){
            messageList.value=response.data
        }else{
            ElMessage.error(`获取消息异常，${response.msg}`)
        }
    }

    async function getAllClassList() {
        const response=(await request.get(`/user/class/getAllClassList?input=${allClassSearch.value}`)).data
        if(response.code===200){
            allClassList.value=response.data
        }else{
            ElMessage.error(`获取异常，${response.msg}`)
        }
        
    }




    

    const sid=uuidv4()

    let ws;
    function socketConnect(){
        ws=new WebSocket(`ws://localhost:63040/user/connect/${sid}/${getCookie("satoken")}`)
       
        // ws=new WebSocket(`ws://122.51.17.127/socket/user/connect/${sid}/${getCookie('satoken')}`)
        ws.onopen=()=>{
            status.value="与服务器连接成功"
        }

        ws.onclose=()=>{
            status.value="与服务器断开连接"
        }

        ws.onerror=(error)=>{
            ElMessage.error( `发生错误,请尝试刷新重连`)
        }

        ws.onmessage=async function(message){
            const res:Message=JSON.parse(message.data)
            if(chooseClass.value!=undefined && chooseClass.value!=null && chooseClass?.value.id==res.classId ){
                messageList.value.push(res)
                await nextTick()
                scrollRef.value.scrollTop = scrollRef.value.scrollHeight

            }else{
                const find =classInfo.value.find(c=>c.id==res.classId)
                if(find){
                    if(find.newMessage){
                        find.newMessage++
                    }else find.newMessage=1;
                }
            }

        }
    }

    function socketUnConnect(){
        if(ws)ws.close()
    }



    function getCookie(name) {
        let matches = document.cookie.match(new RegExp(
          "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
        ));
        return matches ? decodeURIComponent(matches[1]) : undefined;
      }

    

    return {classInfo,classSearch,chooseClass,input,getMessageParm,messageList,scrollRef,allClassSearch,allClassList,
        getAllClassList,socketConnect,socketUnConnect,getMessage,sendMessage,getUserClass}
}